package com.text.mqtt_text.service.impl;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.text.mqtt_text.pojo.Info;
import com.text.mqtt_text.service.MqttService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class MqttServiceImpl implements MqttService {

    private static final Logger log = LoggerFactory.getLogger(MqttServiceImpl.class);
    private int body;//坐姿0表示坐姿正常，1表示不正常
    private double head;//额头温度
    private double humidity;//湿度
    private double temperature;//温度
    private MqttClient client;

    @PostConstruct
    public void init() {
        try {
            String broker = "ssl://k1a8gKQzYMD.iot-as-mqtt.cn-shanghai.aliyuncs.com:443";
            String clientId = "k207mk3MJSI.QPrUT20sCr3Ilp6EtyKQ|securemode=2,signmethod=hmacsha256,timestamp=1745852309050|";
            String username = "QPrUT20sCr3Ilp6EtyKQ&k207mk3MJSI";
            String password = "984bd074b15368a405045df0a36317c5c34e3b48a046538bee59afeefdee9d86";

            client = new MqttClient(broker, clientId);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setCleanSession(true);
            options.setAutomaticReconnect(true);
            options.setConnectionTimeout(30);
            options.setKeepAliveInterval(60);

            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    while (!client.isConnected()) {
                        try {
                            client.connect(options);
                            Thread.sleep(5000); // 5秒后重连
                        } catch (Exception e) {

                        }
                    }
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    String payload = new String(message.getPayload());
                    JsonElement element = JsonParser.parseString(payload);
                    if (!element.isJsonObject()) {
                        log.warn("Invalid JSON format: {}", payload);
                        return;
                    }

                    JsonObject obj = element.getAsJsonObject();
                    String deviceName = obj.has("deviceName") ? obj.get("deviceName").getAsString() : "Unknown";
                    JsonObject items = obj.has("items") ? obj.getAsJsonObject("items") : null;

                    if (items != null && items.has("T") && items.has("ET")&& items.has("H")&& items.has("S")) {
                        double currentBodyValue = items.getAsJsonObject("S").getAsJsonPrimitive("value").getAsInt();
                        double currentHeadValue = items.getAsJsonObject("ET").getAsJsonPrimitive("value").getAsFloat();
                        double currentHumidityValue = items.getAsJsonObject("H").getAsJsonPrimitive("value").getAsFloat();
                        double currentTemperatureValue = items.getAsJsonObject("T").getAsJsonPrimitive("value").getAsFloat();


                        synchronized (this) { // 确保线程安全
                            body= (int) currentBodyValue;
                            head=currentHeadValue;
                            temperature = currentTemperatureValue;
                            humidity = currentHumidityValue;
                        }

                        log.info("body:{},head:{},humidity:{},temperature:{}", body, head, humidity, temperature);
                    } else {
                        log.warn("Missing required fields in message: {}", payload);
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 忽略
                }
            });

            client.connect(options);
            client.subscribe("/k207mk3MJSI/QPrUT20sCr3Ilp6EtyKQ/user/study");
        } catch (Exception e) {
            log.error("Failed to initialize MQTT client: {}", e.getMessage(), e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (client != null && client.isConnected()) {
            try {
                client.disconnect();
            } catch (MqttException e) {
                log.error("Failed to disconnect MQTT client: {}", e.getMessage(), e);
            }
        }
    }

    @Override
    public Info receiveMessage() {
        synchronized (this) {
            return new Info(body,head,humidity,temperature);
        }
    }
}
